package cn.edu.zjicm.wordsnet_d.data;

import java.util.List;

import android.content.Context;
import cn.edu.zjicm.wordsnet_d.BroadcastReceiver.AlarmReceiver;
import cn.edu.zjicm.wordsnet_d.activity.DataToRestActivity;
import cn.edu.zjicm.wordsnet_d.app.WordApp;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference.BookType;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference.StudyMode;
import cn.edu.zjicm.wordsnet_d.db.WordFactory;
import cn.edu.zjicm.wordsnet_d.util.DateTimeUtils;
import cn.edu.zjicm.wordsnet_d.util.LogUtil;

public class DataManager {

	private static DataManager instantce;
	// private ArrayList<OneWord> mUnFamiliarList, mFamiliarList, mTooEasyList;
	// // mUnlearnList
	private int addToUnFamiliarWordNum, addToFamiliarWordNum;

	private DataManager() {

	}

	public static DataManager getInstance() {
		if (instantce == null) {
			instantce = new DataManager();
		}
		return instantce;
	}

	// 重设学习计划,从旧版本同步上来，将单词书进行拆分
	public void resetStudyPlan(Context context, int bookID, int year, int month, int day, int planStartDate) {

		splitStudyPlan(context, bookID, year, month, day, planStartDate);

		// 改变单词书，修改统计中的未学单词个数
		int allUnlearnedCount = getAllUnlearnedCount(context);
		AppPreference.setNewWordsFmDegree(context, allUnlearnedCount, 0);
		AppPreference.setWordsFmDegree(context, allUnlearnedCount, 0);

		reset(context);

		// 设置友盟自定义事件
		MobclickAgentData.setBook(context, bookID);
	}

	public int getAllUnlearnedCount(Context context) {
		int allUnlearnedCount = 0;
		WordFactory wf = WordFactory.getInstance(context);
		if (StudyPlan.isLearningWordBook(context)) {
			allUnlearnedCount += wf.getUnLearnedWordCount(AppPreference.getWordBookIndex(context));
		}
		if (StudyPlan.isLearningPhraseBook(context)) {
			allUnlearnedCount += wf.getUnLearnedWordCount(AppPreference.getPhraseBookIndex(context));
		}
		return allUnlearnedCount;
	}

	/**
	 * 拆分学习计划
	 * 
	 * @param context
	 */
	public void splitStudyPlan(Context context, int bookID, int year, int month, int day, int planStartDate) {
		int oldBookIndex = bookID;
		int newWordBookIndex = -1, newPhraseBookIndex = -1;
		if (oldBookIndex != -1) {
			if (oldBookIndex == 20) { // 中考单词+词组
				newWordBookIndex = 7; // 中考必备单词
				newPhraseBookIndex = 18; // 中考必备词组

			} else if (oldBookIndex == 21) { // 高考单词+词组
				newWordBookIndex = 3; // 高考单词
				newPhraseBookIndex = 19; // 高考词组

			} else if (oldBookIndex == 102) { // 四级单词+词组
				newWordBookIndex = 0; // 大学英语四级
				newPhraseBookIndex = 101; // 四级词组

			} else if (oldBookIndex == 107) { // 六级单词+词组
				newWordBookIndex = 1; // 六级单词
				newPhraseBookIndex = 106; // 六级词组

			} else if (oldBookIndex == 105) { // 考研单词+词组
				newWordBookIndex = 2; // 考研单词
				newPhraseBookIndex = 103; // 考研词组

			} else if (oldBookIndex == 109) { // 雅思单词+词组
				newWordBookIndex = 8; // 雅思单词
				newPhraseBookIndex = 108; // 雅思词组

			} else if (oldBookIndex == 111) { // 托福单词+词组
				newWordBookIndex = 9; // 托福单词
				newPhraseBookIndex = 110; // 托福词组

			} else if (oldBookIndex == 18 || oldBookIndex == 19 || oldBookIndex == 101 || oldBookIndex == 106 || oldBookIndex == 103 || oldBookIndex == 104 || oldBookIndex == 108
					|| oldBookIndex == 110) {// 中考词组，高考词组，四级词组，六级词组，考研核心词组，考研补充词组，雅思词组，托福词组
				newPhraseBookIndex = oldBookIndex;
			} else {
				newWordBookIndex = oldBookIndex;
			}

			if (newWordBookIndex != -1) {
				StudyPlan wordStudyPlan = new StudyPlan();
				wordStudyPlan.setBookIndex(newWordBookIndex);
				wordStudyPlan.setBookType(BookType.BOOK_WORD);
				wordStudyPlan.setLearning(true);
				wordStudyPlan.setStudyMode(StudyMode.MODE_END_TIME); // 从旧版本升上来的都是设置截止时间的
				wordStudyPlan.setEndYear(year);
				wordStudyPlan.setEndMonth(month);
				wordStudyPlan.setEndDay(day);
				wordStudyPlan.setStartPlanTime(planStartDate);
				wordStudyPlan.savePlan(context);

			}
			if (newPhraseBookIndex != -1) {
				StudyPlan phraseStudyPlan = new StudyPlan();
				phraseStudyPlan.setBookIndex(newPhraseBookIndex);
				phraseStudyPlan.setBookType(BookType.BOOK_PHRASE);
				phraseStudyPlan.setLearning(true);
				phraseStudyPlan.setStudyMode(StudyMode.MODE_END_TIME); // 从旧版本升上来的都是设置截止时间的
				phraseStudyPlan.setEndYear(year);
				phraseStudyPlan.setEndMonth(month);
				phraseStudyPlan.setEndDay(day);
				phraseStudyPlan.setStartPlanTime(planStartDate);
				phraseStudyPlan.savePlan(context);

			}

			LogUtil.d("原单词书:" + oldBookIndex + ",新单词书:" + newWordBookIndex + ",新词组书:" + newPhraseBookIndex);
		}
	}

	/**
	 * 登录注册同步时用
	 * 
	 * @param context
	 * @param word_book_id
	 * @param wordPlanStartDate
	 * @param wordIsLearning
	 * @param wordStudyMode
	 * @param wordPlanEndDate
	 * @param wordEveryDayNum
	 */
	public void resetWordStudyPlan(Context context, int word_book_id, int wordPlanStartDate, boolean wordIsLearning, int wordStudyMode, int wordPlanEndDate, int wordEveryDayNum) {
		AppPreference.setWordBookIndex(context, word_book_id);
		AppPreference.setWordPlanStartDate(context, wordPlanStartDate);
		AppPreference.setWordBookIsLearning(context, wordIsLearning);
		AppPreference.setWordStudyMode(context, wordStudyMode);
		AppPreference.setWordPlanEndYear(context, wordPlanEndDate / 10000);
		AppPreference.setWordPlanEndMonth(context, wordPlanEndDate / 100 % 100 - 1);
		AppPreference.setWordPlanEndDay(context, wordPlanEndDate % 100);
		AppPreference.setWordEveryDayNumber(context, wordEveryDayNum);
	}

	/**
	 * 登录注册同步时用
	 * 
	 * @param context
	 * @param word_book_id
	 * @param wordPlanStartDate
	 * @param wordIsLearning
	 * @param wordStudyMode
	 * @param wordPlanEndDate
	 * @param wordEveryDayNum
	 */
	public void resetPhraseStudyPlan(Context context, int phrase_book_id, int phrasePlanStartDate, boolean phraseIsLearning, int phraseStudyMode, int phrasePlanEndDate, int phraseEveryDayNum) {
		AppPreference.setPhraseBookIndex(context, phrase_book_id);
		AppPreference.setPhrasePlanStartDate(context, phrasePlanStartDate);
		AppPreference.setPhraseBookIsLearning(context, phraseIsLearning);
		AppPreference.setPhraseStudyMode(context, phraseStudyMode);
		AppPreference.setPhrasePlanEndYear(context, phrasePlanEndDate / 10000);
		AppPreference.setPhrasePlanEndMonth(context, phrasePlanEndDate / 100 % 100 - 1);
		AppPreference.setPhrasePlanEndDay(context, phrasePlanEndDate % 100);
		AppPreference.setPhraseEveryDayNumber(context, phraseEveryDayNum);
	}

	// 在设置中重设学习计划 v2.11.0 add by ct
	public void resetStudyPlan(Context context) {
		int allUnLearnedCount = getAllUnlearnedCount(context);

		LogUtil.d("修改前,newWordsFmDegree=" + AppPreference.getNewWordsFmDegree(context, 0));
		AppPreference.setNewWordsFmDegree(context, allUnLearnedCount, 0);
		AppPreference.setWordsFmDegree(context, allUnLearnedCount, 0);
		LogUtil.d("修改后,newWordsFmDegree=" + AppPreference.getNewWordsFmDegree(context, 0));
		reset(context);
	}

	// 添加学习计划 v2.11.0 add by ct
	public void addStudyPlan(Context context, StudyPlan studyPlan) {
		// 保存学习计划
		studyPlan.savePlan(context);

		// 改变单词书，修改统计中的未学单词个数
		WordFactory wf = WordFactory.getInstance(context);
		int unlearnedWordCount = wf.getUnLearnedWordCount(studyPlan.getBookIndex());

		int oldNewWordsFmDegree = AppPreference.getNewWordsFmDegree(context, 0);
		int oldWordsFmDegree = AppPreference.getWordsFmDegree(context, 0);

		LogUtil.d("添加前,unlearnedWordCount=" + unlearnedWordCount + ",oldNewWordsFmDegree=" + oldNewWordsFmDegree + ",oldWordsFmDegree=" + oldWordsFmDegree);

		AppPreference.setNewWordsFmDegree(context, unlearnedWordCount + oldNewWordsFmDegree, 0);
		AppPreference.setWordsFmDegree(context, unlearnedWordCount + oldWordsFmDegree, 0);

		LogUtil.d("添加后,oldNewWordsFmDegree=" + AppPreference.getNewWordsFmDegree(context, 0) + ",oldWordsFmDegree=" + AppPreference.getWordsFmDegree(context, 0));
		reset(context);

	}

	/**
	 * 添加或修改完学习计划后，需要重置
	 */
	private void reset(Context context) {
		// 清除原未学单词队列
		DataManager.getInstance().clearPlanToLearnWordList(context);

		// 加推新词
		if (AppPreference.getWordBookIndex(context) != -1 || AppPreference.getPhraseBookIndex(context) != -1) {
			addWordsForStudy(context);
			AppPreference.setReviewDate(context, -1);
			setTodayStudyPlan(context);
		}

		AlarmReceiver.alarmCheckStudy(context);
		AppPreference.setFirstTimeStudyNewBook(context, true);

		DataToRestActivity mDataToRestActivity = DataToRestActivity.getInstance();
		mDataToRestActivity.setDBChanged(true);
	}

	// 清空用户数据
	public void clearUserData(Context context) {
		StudyPlan.clearWordStudyPlan(context);
		StudyPlan.clearPhraseStudyPlan(context);

		// 清除学习时间，20141113添加
		AppPreference.setStudyDate(context, -1);
		AppPreference.setReviewDate(context, -1);

		for (int i = 0; i < 7; i++) {
			AppPreference.setWordsFmDegree(context, 0, i);
			AppPreference.setNewWordsFmDegree(context, 0, i);
		}

		WordFactory.getInstance(context).deleteTableWordsLog();
		WordFactory.getInstance(context).deleteTablePunchLog();
		WordFactory.getInstance(context).deleteTableOrderLog();
		WordFactory.getInstance(context).setZMD(0); // 将zmd设置为0
		AppPreference.setDownloadPunchData(context, false);

		// mUnFamiliarList = new ArrayList<OneWord>();
		// mFamiliarList = new ArrayList<OneWord>();
		// mTooEasyList = new ArrayList<OneWord>();

		AppPreference.clearSelectedBookId(context);

		DataToRestActivity mDataToRestActivity = DataToRestActivity.getInstance();
		mDataToRestActivity.setDBChanged(true);
	}

	// 根据学习进度往生词列表添加单词
	public void doStudyProgress(Context context) {
		LogUtil.d("调用doStudyProgress()");
		int today = DateTimeUtils.getDate();
		int lastStudyDate = AppPreference.getStudyDate(context);
		// LogUtil.addLog("原学习日期为" + lastStudyDate);
		if (lastStudyDate == -1 || lastStudyDate != today || isLastDay(context, BookType.BOOK_WORD) || isLastDay(context, BookType.BOOK_PHRASE)) {
			addWordsForStudy(context);

			// 当天的第一次运行，将现在的统计数据更新为昨天的数据
			for (int i = 0; i < 7; i++)
				AppPreference.setWordsFmDegree(context, AppPreference.getNewWordsFmDegree(context, i), i);
		}
		setTodayStudyPlan(context);
		// 旧用户更新到这一版本后第一次调用时使用，以后不用通过数据库获取
		/*
		 * if (AppPreference.getIsFirstUseThisVersion(context) && lastStudyDate
		 * != -1) { LogActivity.addLog("更新熟悉度统计");
		 * countNewWordsFmDegree(context); for (int i = 0; i < 6; i++)
		 * AppPreference.setWordsFmDegree(context,
		 * AppPreference.getNewWordsFmDegree(context, i), i);
		 * AppPreference.setIsFirstUseThisVersion(context, false); }
		 */
		// AlarmReceiver.alarmAddWord(context);
		AlarmReceiver.alarmCheckStudy(context);
	}

	/**
	 * 超过截止日期的要全部推送 v2.11.0 add by ct
	 * 
	 * @param context
	 * @param bookType
	 * @return
	 */
	private boolean isLastDay(Context context, int bookType) {
		if (bookType == BookType.BOOK_WORD) {
			return StudyPlan.isLearningWordBook(context) && DateTimeUtils.getPlanLastDay(context, bookType) <= 0;
		} else if (bookType == BookType.BOOK_PHRASE) {
			return StudyPlan.isLearningPhraseBook(context) && DateTimeUtils.getPlanLastDay(context, bookType) <= 0;
		}
		return false;
	}

	// 计算单词统计个数
	public void countNewWordsFmDegree(Context context) {
		WordFactory wf = WordFactory.getInstance(context);

		wf.updateUnfamilarWordSenseDegree();
		// wf.count();

		AppPreference.setNewWordsFmDegree(context, wf.getUnLearnedWordCount(), 0);
		AppPreference.setNewWordsFmDegree(context, wf.getWordsFmDegree(1), 1);
		AppPreference.setNewWordsFmDegree(context, wf.getWordsFmDegree(2), 2);
		AppPreference.setNewWordsFmDegree(context, wf.getWordsFmDegree(3), 3);
		AppPreference.setNewWordsFmDegree(context, wf.getWordsFmDegree(4), 4);
		AppPreference.setNewWordsFmDegree(context, wf.getFamiliarWordCount(), 5);
		AppPreference.setNewWordsFmDegree(context, wf.getTooEasyWordCount(), 6);

		for (int i = 0; i < 7; i++)
			AppPreference.setWordsFmDegree(context, AppPreference.getNewWordsFmDegree(context, i), i);
	}

	// 清除待学单词
	public void clearPlanToLearnWordList(Context context) {
		WordFactory wf = WordFactory.getInstance(context);
		// LogUtil.addLog("清除未学单词开始");
		wf.deleteFromUnFamiliarWordList();
		// LogUtil.addLog("清除未学单词完成");
	}

	// 推送新词 v2.11.0 add by ct
	public void addWordsForStudy(Context context) {
		WordFactory wf = WordFactory.getInstance(context);
		int wordNum = DateTimeUtils.getWordBookNumPerDayForPlan(context, false);
		int phraseNum = DateTimeUtils.getPhraseBookNumPerDayForPlan(context, false);

		int overDateWordCount = wf.getPlanToLearnedWordCount(); // 在学习今天单词前，word_log表中未学的单词个数
		if (overDateWordCount > 0) { // 清除掉今天之前放入到word_log表中的未学单词
			wf.deleteFromUnFamiliarWordList();
		}

		// 将新的单词和词组加入
		int wordBookIndex = AppPreference.getWordBookIndex(context);
		int phraseBookIndex = AppPreference.getPhraseBookIndex(context);
		if (StudyPlan.isLearningWordBook(context)) {
			wf.addToUnFamiliarWordList(wordNum, wordBookIndex);
			LogUtil.d("推送单词:" + wordNum + "个");
		}
		if (StudyPlan.isLearningPhraseBook(context)) {
			wf.addToUnFamiliarWordList(phraseNum, phraseBookIndex);
			LogUtil.d("推送词组:" + phraseNum + "个");
		}

		// 修改当前日期
		int today = DateTimeUtils.getDate();
		AppPreference.setStudyDate(context, today);
	}

	// 设置当天学习计划
	public void setTodayStudyPlan(Context context) {
		LogUtil.d("调用setTodayStudyPlan()");
		int today = DateTimeUtils.getDate();
		int lastReviewDate = AppPreference.getReviewDate(context);
		if (lastReviewDate == -1 || lastReviewDate != today) {
			AppPreference.setTodayStudyNewWordCount(context, 0);
			AppPreference.setTodayReviewWordCount(context, 0);
			AppPreference.setTodayShouldReviewWordCount(context, WordFactory.getInstance(context).getNumberOfWordsTodayShouldReview(OneWord.DEGREE_UNFAMILIAR));
			AppPreference.setReviewDate(context, today);
		}
	}

	// 加量学习
	public void addExtraWordsForStudy(Context context, int num) {
		WordFactory wf = WordFactory.getInstance(context);
		// LogUtil.addLog("推送新词" + num + "个开始");
		wf.addToUnFamiliarWordList(num);
		// LogUtil.addLog("推送新词" + num + "个完成");
	}

	// 初始化列表
	// public void init(Context context) {
	// mUnFamiliarList = new ArrayList<OneWord>();
	// mFamiliarList = new ArrayList<OneWord>();
	// mTooEasyList = new ArrayList<OneWord>();
	//
	// WordFactory wf = WordFactory.getInstance(context);
	// mUnFamiliarList.addAll(wf.getUnFamiliarWords());
	// mFamiliarList.addAll(wf.getFamiliarWords());
	// mTooEasyList.addAll(wf.getTooEasyWords());
	// }

	// public ArrayList<OneWord> getWordList(int wordDegress, Context context) {
	// if (mUnFamiliarList == null || mFamiliarList == null || mTooEasyList ==
	// null)
	// init(context);
	//
	// switch (wordDegress) {
	// case OneWord.DEGREE_UNFAMILIAR:
	// return mUnFamiliarList;
	// case OneWord.DEGREE_FAMILIAR:
	// return mFamiliarList;
	// case OneWord.SENSE_DEGREE_TOO_EASY:
	// return mTooEasyList;
	// case OneWord.SENSE_DEGREE_TOO_EASY_FROM_CONSOLIDATE:
	// return mTooEasyList;
	// }
	// return null;
	// }

	public OneWord findWord(OneWord w, Context context) {

		WordFactory wf = WordFactory.getInstance(context);
		w = wf.getOneWordById(w.getIndex_word_id());
		int familiarDegree = w.getDegree_fm();
		if (w.getDegree_fm() == OneWord.DEGREE_UNFAMILIAR && w.getSense_degree_fm() == 0) {
			// familiarDegree = OneWord.DEGREE_UNLEARN;
			return null;
		} else if (w.getDegree_fm() == OneWord.DEGREE_FAMILIAR && w.getSense_degree_fm() < OneWord.SENSE_DEGREE_TOO_EASY)
			familiarDegree = OneWord.DEGREE_FAMILIAR;
		else if (w.getDegree_fm() == OneWord.DEGREE_FAMILIAR && w.getSense_degree_fm() == OneWord.SENSE_DEGREE_TOO_EASY)
			familiarDegree = OneWord.SENSE_DEGREE_TOO_EASY;
		else if (w.getDegree_fm() == OneWord.DEGREE_FAMILIAR && w.getSense_degree_fm() == OneWord.SENSE_DEGREE_TOO_EASY_FROM_CONSOLIDATE)
			familiarDegree = OneWord.SENSE_DEGREE_TOO_EASY_FROM_CONSOLIDATE;

		return wf.getOneWordByIndexWordID(w.getIndex_word_id(), familiarDegree);

	}

	// 将生词升级为熟词
	public void changeUnFamiliarToFamiliar(OneWord word, Context context) {
		int oldDegree = getWordDegreeType(word.getSense_degree_fm()); // OneWord.SENSE_DEGREE_UNFAMILIAR4_TYPE;
		int newDegree = OneWord.SENSE_DEGREE_FAMILIAR_TYPE;
		// 生词减一， 熟词加一
		AppPreference.setNewWordsFmDegree(context, AppPreference.getNewWordsFmDegree(context, oldDegree) - 1, oldDegree);
		AppPreference.setNewWordsFmDegree(context, AppPreference.getNewWordsFmDegree(context, newDegree) + 1, newDegree);
		DataToRestActivity.getInstance().setDBChanged(true);

		// word.setSense_degree_fm(OneWord.SENSE_DEGREE_FAMILIAR);
		// WordFactory.getInstance(context).updateWordSenseFamiliarDegree(word);
		// word.setDegree_fm(OneWord.DEGREE_FAMILIAR);
		// WordFactory.getInstance(context).markWordDegree(word.getIndex_word_id(),
		// OneWord.DEGREE_FAMILIAR);
		// WordFactory.getInstance(context).updateNextConsolidateTime(word.getIndex_word_id(),
		// (DateTimeUtils.getTimeOfMinuteWithZoneRawOffsetTime() + 7 *
		// DateTimeUtils.MINUTES_OF_DAY));
		// word.setLast_test_time(DateTimeUtils.getTimeOfMinuteWithZoneRawOffsetTime());
		// WordFactory.getInstance(context).updateCurrentWordTestTime(word);
		// word.setSense_degree_fm(OneWord.SENSE_DEGREE_FAMILIAR);
		// word.setDegree_fm(OneWord.DEGREE_FAMILIAR);
		WordFactory.getInstance(context).initConsolidateWord(word, 7);

		changeWordDegree(word, OneWord.DEGREE_UNFAMILIAR, OneWord.DEGREE_FAMILIAR, context);
		// WordApp.getAppInstance()
		// .notifyWordDegreeChange(OneWord.DEGREE_UNFAMILIAR, word);
		WordApp.getInstance().notifyInstantiateItem(0);
		WordApp.getInstance().notifyInstantiateItem(1);
	}

	// 将生词词转为太简单
	public void changeUnFamiliarToTooEasy(OneWord word, Context context) {
		int oldDegree = getWordDegreeType(word.getSense_degree_fm()); // OneWord.SENSE_DEGREE_UNFAMILIAR4_TYPE;
		int newDegree = OneWord.SENSE_DEGREE_TOO_EASY_TYPE;

		AppPreference.setNewWordsFmDegree(context, AppPreference.getNewWordsFmDegree(context, newDegree) + 1, newDegree);
		AppPreference.setNewWordsFmDegree(context, AppPreference.getNewWordsFmDegree(context, oldDegree) - 1, oldDegree);
		DataToRestActivity.getInstance().setDBChanged(true);

		word.setSense_degree_fm(OneWord.SENSE_DEGREE_TOO_EASY);
		WordFactory.getInstance(context).updateWordSenseFamiliarDegree(word);
		word.setDegree_fm(OneWord.DEGREE_FAMILIAR);
		WordFactory.getInstance(context).markWordDegree(word.getIndex_word_id(), OneWord.DEGREE_FAMILIAR);

		// 将单词加入到太简单列表
		changeWordDegree(word, OneWord.DEGREE_UNFAMILIAR, OneWord.SENSE_DEGREE_TOO_EASY, context);

		// WordApp.getAppInstance()
		// .notifyWordDegreeChange(OneWord.DEGREE_FAMILIAR, word);
		WordApp.getInstance().notifyInstantiateItem(0);
		WordApp.getInstance().notifyInstantiateItem(2);
	}

	// 将未学单词转为生词
	public void changeUnLearnToUnFamiliar(OneWord word, Context context, boolean flag) {
		// true表示此方法由从搜索过程中点击添加到生词本调用，false表示是从学习点击太简单调用，
		// 因为点击太简单会在调用这个函数的后面添加一次，所以此处不需要添加
		int oldDegree = OneWord.SENSE_DEGREE_UNLEARN_TYPE;
		int newDegree = OneWord.SENSE_DEGREE_UNFAMILIAR1_TYPE;
		if (flag) {
			// 如果要加入生词本的单词属于当前单词书，未学单词个数-1，否则未学单词个数不变
			if (WordFactory.getInstance(context).isContainInRecentBook(word.getIndex_word_id())) {
				AppPreference.setNewWordsFmDegree(context, AppPreference.getNewWordsFmDegree(context, oldDegree) - 1, oldDegree);
			}
			if (!WordFactory.getInstance(context).isContainerInWordLog(word.getIndex_word_id())) {
				LogUtil.d("新加单词不在word_log表中");
				removeSomeWordsFromWordLog(context); // 要求新加的单词不在word_log表中
			} else {
				LogUtil.d("新加单词在word_log表中");
			}

			AppPreference.setNewWordsFmDegree(context, AppPreference.getNewWordsFmDegree(context, newDegree) + 1, newDegree);
			DataToRestActivity.getInstance().setDBChanged(true);

		}

		// 词义熟悉度设为1
		word.setSense_degree_fm(OneWord.SENSE_DEGREE_UNFAMILIAR0);
		WordFactory.getInstance(context).updateWordSenseFamiliarDegree(word);
		word.setDegree_fm(OneWord.DEGREE_UNFAMILIAR);
		WordFactory.getInstance(context).markWordDegree(word.getIndex_word_id(), OneWord.DEGREE_UNFAMILIAR);

		changeWordDegree(word, OneWord.DEGREE_UNLEARN, OneWord.DEGREE_UNFAMILIAR, context);
		WordApp.getInstance().notifyInstantiateItem(0);
	}

	private void removeSomeWordsFromWordLog(Context context) {
		LogUtil.d("调用removeSomeWordsFromWordLog()");

		int wordBookStudyMode = StudyPlan.getWordBookStudyMode(context);
		int phraseBookStudyMode = StudyPlan.getPhraseBookStudyMode(context);

		if (wordBookStudyMode == StudyMode.MODE_NUMBER && phraseBookStudyMode == StudyMode.MODE_NUMBER) { // 两个计划都是按照每日学习个数来
			LogUtil.d("两个计划都是按照每日学习个数来");
			double wordPerDayCount = DateTimeUtils.getWordBookNumPerDayForPlan(context, false);
			double phrasePerDayCount = DateTimeUtils.getPhraseBookNumPerDayForPlan(context, false);
			double all = wordPerDayCount + phrasePerDayCount;
			double wordRate = wordPerDayCount / all; // 单词书占的比例
			double random = Math.random();
			LogUtil.d("random=" + random + ",wordRate=" + wordRate);
			if (random <= wordRate) { // 剔除word_log中的一个单词
				WordFactory.getInstance(context).randomDeleteWord();
				// 这里是否需要将newWordsFmDegree进行修改？

			} else {// 剔除word_log中的一个词组
				WordFactory.getInstance(context).randomDeletePhrase();
			}
		} else if (wordBookStudyMode == StudyMode.MODE_NUMBER) {
			LogUtil.d("单词书是按照每日学习个数来");
			WordFactory.getInstance(context).randomDeleteWord();

		} else if (phraseBookStudyMode == StudyMode.MODE_NUMBER) {
			LogUtil.d("词组书是按照每日学习个数来");
			WordFactory.getInstance(context).randomDeletePhrase();
		}

	}

	// 将生词转为未学单词
	public void changeUnFamiliarToUnLearn(OneWord word, Context context) {
		int oldDegree = OneWord.SENSE_DEGREE_UNFAMILIAR1_TYPE;
		int newDegree = OneWord.SENSE_DEGREE_UNLEARN_TYPE;

		AppPreference.setNewWordsFmDegree(context, AppPreference.getNewWordsFmDegree(context, oldDegree) - 1, oldDegree);
		// 如果要加入生词本的单词属于当前单词书，未学单词个数-1，否则未学单词个数不变
		if (WordFactory.getInstance(context).isContainInRecentBook(word.getIndex_word_id()))
			AppPreference.setNewWordsFmDegree(context, AppPreference.getNewWordsFmDegree(context, newDegree) + 1, newDegree);
		DataToRestActivity.getInstance().setDBChanged(true);

		// 词义熟悉度设为1
		word.setSense_degree_fm(OneWord.SENSE_DEGREE_UNLEARN);
		WordFactory.getInstance(context).updateWordSenseFamiliarDegree(word);
		word.setDegree_fm(OneWord.DEGREE_UNLEARN);
		WordFactory.getInstance(context).markWordDegree(word.getIndex_word_id(), OneWord.DEGREE_UNLEARN);

		changeWordDegree(word, OneWord.DEGREE_UNFAMILIAR, OneWord.DEGREE_UNLEARN, context);
		WordApp.getInstance().notifyInstantiateItem(0);
	}

	// 将熟词转为生词
	public void changeFamiliarToUnFamiliar(OneWord word, Context context) {
		int oldDegree = OneWord.SENSE_DEGREE_FAMILIAR_TYPE;
		int newDegree = OneWord.SENSE_DEGREE_UNFAMILIAR1_TYPE;
		// 熟词减一， 生词加一
		AppPreference.setNewWordsFmDegree(context, AppPreference.getNewWordsFmDegree(context, oldDegree) - 1, oldDegree);
		AppPreference.setNewWordsFmDegree(context, AppPreference.getNewWordsFmDegree(context, newDegree) + 1, newDegree);
		DataToRestActivity.getInstance().setDBChanged(true);
		// Log.i("changeFamiliarToUnFamiliar", oldDegree+".......");

		// 词义熟悉度设为0
		word.setSense_degree_fm(OneWord.SENSE_DEGREE_UNFAMILIAR1);
		WordFactory.getInstance(context).updateWordSenseFamiliarDegree(word);
		word.setDegree_fm(OneWord.DEGREE_UNFAMILIAR);
		WordFactory.getInstance(context).markWordDegree(word.getIndex_word_id(), OneWord.DEGREE_UNFAMILIAR);

		changeWordDegree(word, OneWord.DEGREE_FAMILIAR, OneWord.DEGREE_UNFAMILIAR, context);
		WordApp.getInstance().notifyInstantiateItem(0);
		WordApp.getInstance().notifyInstantiateItem(1);
	}

	// 将太简单转为生词
	public void changeTooEasyToUnFamiliar(OneWord word, Context context) {
		int oldDegree = OneWord.SENSE_DEGREE_TOO_EASY_TYPE;
		int newDegree = OneWord.SENSE_DEGREE_UNFAMILIAR1_TYPE;
		// 熟词减一， 生词加一
		AppPreference.setNewWordsFmDegree(context, AppPreference.getNewWordsFmDegree(context, oldDegree) - 1, oldDegree);
		AppPreference.setNewWordsFmDegree(context, AppPreference.getNewWordsFmDegree(context, newDegree) + 1, newDegree);
		DataToRestActivity.getInstance().setDBChanged(true);
		// Log.i("changeFamiliarToUnFamiliar", oldDegree+".......");

		// 词义熟悉度设为0
		word.setSense_degree_fm(OneWord.SENSE_DEGREE_UNFAMILIAR1);
		WordFactory.getInstance(context).updateWordSenseFamiliarDegree(word);
		word.setDegree_fm(OneWord.DEGREE_UNFAMILIAR);
		WordFactory.getInstance(context).markWordDegree(word.getIndex_word_id(), OneWord.DEGREE_UNFAMILIAR);

		changeWordDegree(word, OneWord.SENSE_DEGREE_TOO_EASY, OneWord.DEGREE_UNFAMILIAR, context);
		WordApp.getInstance().notifyInstantiateItem(0);
		WordApp.getInstance().notifyInstantiateItem(2);
	}

	// 将熟词转为太简单
	public void changeFamiliarToTooEasy(OneWord word, Context context) {
		int oldDegree = OneWord.SENSE_DEGREE_FAMILIAR_TYPE;
		int newDegree = OneWord.SENSE_DEGREE_TOO_EASY_TYPE;
		AppPreference.setNewWordsFmDegree(context, AppPreference.getNewWordsFmDegree(context, newDegree) + 1, newDegree);
		AppPreference.setNewWordsFmDegree(context, AppPreference.getNewWordsFmDegree(context, oldDegree) - 1, oldDegree);
		DataToRestActivity.getInstance().setDBChanged(true);
		// Log.i("WordSenseQuestion", "0........6");

		word.setSense_degree_fm(OneWord.SENSE_DEGREE_TOO_EASY);
		WordFactory.getInstance(context).updateWordSenseFamiliarDegree(word);
		word.setDegree_fm(OneWord.DEGREE_FAMILIAR);
		WordFactory.getInstance(context).markWordDegree(word.getIndex_word_id(), OneWord.DEGREE_FAMILIAR);

		// 将单词加入到太简单列表
		changeWordDegree(word, OneWord.DEGREE_FAMILIAR, OneWord.SENSE_DEGREE_TOO_EASY, context);
		WordApp.getInstance().notifyInstantiateItem(1);
		WordApp.getInstance().notifyInstantiateItem(2);

		// WordApp.getAppInstance()
		// .notifyWordDegreeChange(OneWord.DEGREE_FAMILIAR, word);
	}

	// 将熟词转为太简单(从巩固熟词这边转过来）
	public void changeFamiliarToTooEasyForConsolidate(OneWord word, Context context) {
		int oldDegree = OneWord.SENSE_DEGREE_FAMILIAR_TYPE;
		int newDegree = OneWord.SENSE_DEGREE_TOO_EASY_TYPE;
		AppPreference.setNewWordsFmDegree(context, AppPreference.getNewWordsFmDegree(context, newDegree) + 1, newDegree);
		AppPreference.setNewWordsFmDegree(context, AppPreference.getNewWordsFmDegree(context, oldDegree) - 1, oldDegree);
		DataToRestActivity.getInstance().setDBChanged(true);
		// Log.i("WordSenseQuestion", "0........6");

		word.setSense_degree_fm(OneWord.SENSE_DEGREE_TOO_EASY_FROM_CONSOLIDATE);
		WordFactory.getInstance(context).updateWordSenseFamiliarDegree(word);
		word.setDegree_fm(OneWord.DEGREE_FAMILIAR);
		WordFactory.getInstance(context).markWordDegree(word.getIndex_word_id(), OneWord.DEGREE_FAMILIAR);

		// 将单词加入到太简单列表
		changeWordDegree(word, OneWord.DEGREE_FAMILIAR, OneWord.SENSE_DEGREE_TOO_EASY, context);
		WordApp.getInstance().notifyInstantiateItem(1);
		WordApp.getInstance().notifyInstantiateItem(2);

		// WordApp.getAppInstance()
		// .notifyWordDegreeChange(OneWord.DEGREE_FAMILIAR, word);
	}

	// 将未学单词转为太简单
	public void changeUnLearnToTooEasy(OneWord word, Context context) {
		int oldDegree = OneWord.SENSE_DEGREE_UNLEARN_TYPE;
		int newDegree = OneWord.SENSE_DEGREE_TOO_EASY_TYPE;
		AppPreference.setNewWordsFmDegree(context, AppPreference.getNewWordsFmDegree(context, newDegree) + 1, newDegree);
		AppPreference.setNewWordsFmDegree(context, AppPreference.getNewWordsFmDegree(context, oldDegree) - 1, oldDegree);
		DataToRestActivity.getInstance().setDBChanged(true);
		// Log.i("WordSenseQuestion", "0........6");

		word.setSense_degree_fm(OneWord.SENSE_DEGREE_TOO_EASY);
		WordFactory.getInstance(context).updateWordSenseFamiliarDegree(word);
		word.setDegree_fm(OneWord.DEGREE_FAMILIAR);
		WordFactory.getInstance(context).markWordDegree(word.getIndex_word_id(), OneWord.DEGREE_FAMILIAR);

		// 将单词加入到太简单列表
		changeWordDegree(word, OneWord.DEGREE_UNLEARN, OneWord.SENSE_DEGREE_TOO_EASY, context);

		// WordApp.getAppInstance()
		// .notifyWordDegreeChange(OneWord.DEGREE_FAMILIAR, word);
	}

	// 将生词或熟词转为未学单词
	public void changeWordToUnLearn(OneWord word, Context context) {
		// 词义熟悉度设为0
		int oldDegree = word.getSense_degree_fm();
		// word.setSense_degree_fm(0);
		// WordFactory.getInstance(context).updateWordSenseFamiliarDegree(word);

		// 因为熟悉度为2的也包含在第一级
		if (oldDegree >= 2) {
			oldDegree--;
		}
		// 生词减一， 熟词加一
		AppPreference.setNewWordsFmDegree(context, AppPreference.getNewWordsFmDegree(context, oldDegree) - 1, oldDegree);
		AppPreference.setNewWordsFmDegree(context, AppPreference.getNewWordsFmDegree(context, 0) + 1, 0);

		int familiarDegree = word.getDegree_fm();
		// word.setDegree_fm(OneWord.DEGREE_UNLEARN);
		// WordFactory.getInstance(context)
		// .markWordDegree(word.getIndex_word_id(),
		// OneWord.DEGREE_UNLEARN);
		WordFactory.getInstance(context).deleteFromWordsLog(word.getIndex_word_id()); // 将单词从words_log表删除

		changeWordDegree(word, familiarDegree, OneWord.DEGREE_UNLEARN, context);
		WordApp.getInstance().notifyInstantiateItem(0);
	}

	// 修改单词熟悉度后，调整其在生词或熟词表的位置
	public void changeWordDegree(OneWord word, int fromDegree, int toDegree, Context context) {
		// if (word != null) {
		// if (fromDegree != OneWord.DEGREE_UNLEARN)
		// getWordList(fromDegree, context).remove(word);
		// if (toDegree != OneWord.DEGREE_UNLEARN)
		// getWordList(toDegree, context).add(0, word);
		// }
	}

	// public void updateWord(OneWord word, Context context) {
	// List<OneWord> list = getWordList(word.getDegree_fm(), context);
	// for (int i = 0; i < list.size(); i++) {
	// OneWord w = list.get(i);
	// if (w.getIndex_word_id() == word.getIndex_word_id()) {
	// w.setSense_degree_fm(word.getSense_degree_fm());
	// w.setLast_test_time(word.getLast_test_time());
	// return;
	// }
	// }
	// }

	public OneWord getWord(Context context, int wordId) {
		return WordFactory.getInstance(context).getOneWordById(wordId);
	}

	public List<RelationShip> getRelationShipList(Context context, int wordId) {
		return WordFactory.getInstance(context).getRelationshipOfWord(wordId, 5);
	}

	public Sentence getSentence(Context context, int exa_sentence_id) {
		return WordFactory.getInstance(context).getSentence(exa_sentence_id);
	}

	public void plusAddToUnFamiliarWordNum() {
		addToUnFamiliarWordNum++;
		// WordApp.getAppInstance().notifyUnlearndWordChange();
	}

	public void plusAddToFamiliarWordNum() {
		addToFamiliarWordNum++;
		// WordApp.getAppInstance().notifyUnlearndWordChange();
	}

	public int getAddToUnFamiliarWordNum() {
		return addToUnFamiliarWordNum;
	}

	public int getAddToFamiliarWordNum() {
		return addToFamiliarWordNum;
	}

	/*
	 * 未学 词义熟悉度0 生词-熟悉度1 词义熟悉度10-29 生词-熟悉度2 词义熟悉度30-39 生词-熟悉度3 词义熟悉度40-49
	 * 生词-熟悉度4 词义熟悉度50-59 熟词(熟悉度5) 词义熟悉度60 太简单(熟悉度6) 熟悉度1000
	 */

	public static int getWordDegreeType(int degree) {
		if (degree == 0)
			return 0;
		else if (degree < 30)
			return 1;
		else if (degree < 40)
			return 2;
		else if (degree < 50)
			return 3;
		else if (degree < OneWord.SENSE_DEGREE_FAMILIAR)
			return 4;
		else if (degree == OneWord.SENSE_DEGREE_FAMILIAR)
			return 5;
		else if (degree == OneWord.SENSE_DEGREE_TOO_EASY)
			return 6;
		return -1;
	}

	public void initExp(Context context) {
		int exp;
		WordFactory wf = WordFactory.getInstance(context);
		exp = wf.getWordsFmDegree(1) * 10 + wf.getWordsFmDegree(2) * 20 + wf.getWordsFmDegree(3) * 30 + wf.getWordsFmDegree(4) * 40 + wf.getFamiliarWordCount() * 50 + wf.getTooEasyWordCount() * 50;
		AppPreference.setEXP(context, exp);
	}

	// 初始化用户巩固熟词数据
	public void initForConsilidate(final Context context) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				WordFactory.getInstance(context).initAllConsolidateWords(14);
			}
		}).start();
	}
}
